package models.services.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.log4j.Logger;

public class DBManager {

	private static DBManager instance;
	private Connection conexion;
	private static Logger logger = Logger.getLogger(DBManager.class);

	private DBManager() {
		conectar();
	}

	public static DBManager getInstance() {
		if (instance == null)
			instance = new DBManager();
		return instance;
	}

	private void conectar() {
		Properties prop = PropertiesManager.getInstance().getDBProperties();
		String ip = prop.getProperty("ip");
		String url = "jdbc:mysql://" + ip + "/sistemas";
		String driver = "com.mysql.jdbc.Driver";
		String user = prop.getProperty("user");
		String contra = prop.getProperty("contrasena");
		try {
			Class.forName(driver);
			conexion = DriverManager.getConnection(url, user, contra);
		} catch (Exception e) {
			logger.error(e.getCause(), e);
		}
	}

	public ResultSet consultar(String consulta) {
		try {
			Statement statement = conexion.createStatement();
			return statement.executeQuery(consulta);
		} catch (SQLException e) {
			logger.error(e.getCause(), e);
			return null;
		}
	}

	public boolean borrar(int id, String tabla) {
		String sql = "delete from " + tabla + " where id = " + id;
		try {
			Statement st = conexion.createStatement();
			int delete = st.executeUpdate(sql);
			if (delete == 1) {
				return true;
			} else {
				return false;
			}
		} catch (SQLException e) {
			logger.error(e.getCause(), e);
			return false;
		}
	}

	public int guardarActualizar(String update) {
		int ret = 0;
		try {
			Statement stm = conexion.createStatement();
			ret = stm.executeUpdate(update);
		} catch (SQLException e) {
			logger.error(e.getCause(), e);
			ret = 0;
		}
		return ret;
	}

	public Connection obtenerConnection() {
		return this.conexion;
	}

}
